import mongoose from "mongoose"
import util from "@mazp/util"

const msgSchema = new mongoose.Schema({
  title: {
    type: String,
    unique: true,
    trim: true,
    required: [true, 'Msg must have a title!'],
    maxlength: [15, 'A msg title must have less or equal then 15 characters'],
    minlength: [1, 'A msg title must have more or equal then 1 characters'],
  },
  originTitle: {
    type: String,
    select: false,
  },
  value: {
    type: String,
    required: [true, 'Msg must have a value!'],
    maxlength: [50, 'A msg value must have less or equal then 50 characters'],
    minlength: [1, 'A msg value must have more or equal then 1 characters'],
  },
  isDelete: {
    type: Boolean,
    select: false,
    default: false
  },
  createdAt: {
    type: Date,
    default: Date.now()
  }
})

msgSchema.pre("save", function (next) {
  this.originTitle = this.title
  next();
});
msgSchema.post("save", function (doc, next) {
  // @ts-ignore 在返回对象时不携带该属性
  doc.isDelete = undefined
  doc.originTitle = undefined
  next();
});
msgSchema.pre(/^find/, function (next) {
  this.find({ isDelete: { $eq: false } })
  next();
});
msgSchema.pre("findOneAndUpdate", function (next) {
  // 非删除情况下的更新，需要更新 origin
  let updateContent: Record<string, any> = this.getUpdate() || {}
  if (!updateContent.isDelete) {
    // 添加更新值
    updateContent.title && this.set({ originTitle: updateContent.title })
  }
  // 删除情况
  else {
    this.set({ title: util.randomChars(15) })
  }
  next();
});
export default mongoose.model('Msg', msgSchema)
